'use strict';
exports.main = async (event, context) => {
	const db = uniCloud.databaseForJQL({
		event,
		context
	});
	db.setUser({
		role: ['admin']
	})
	let data = JSON.parse(event.body)
	if (data.method == "getFileList") {
		let fileType = {
			type: data.type
		}
		if (data.type == 'all') {
			fileType = {}
		}
		const fileList = await db.collection("item").where({
			up: data.path,
			user_id: data.key,
			...fileType
		}).orderBy("time", "desc").field(
			"title,dateToString(time,'%Y-%m-%d') as _time,type,content,size,cond(eq(password_mode, true), '', url) as _url,icon,package,version,duration,password_mode"
		).skip((data.page - 1) * data.size).limit(data.size).get();
		return {
			msg: "获取成功",
			code: 200,
			data: fileList.data
		}
	} else if (data.method == "getFileInfo") {
		const fileInfo = await db.collection("item").where({
			_id: data._id,
			user_id: data.key
		}).orderBy("time", "desc").field(
			"title,dateToString(time,'%Y-%m-%d') as _time,type,content,size,cond(eq(password_mode, true), '', url) as _url,icon,package,version,duration,password_mode"
		).get({
			getOne: true
		});
		if (fileInfo.data) {
			return {
				msg: "获取成功",
				code: 200,
				data: fileInfo.data
			}
		} else {
			return {
				msg: "文件不存在",
				code: 400
			}
		}

	} else if (data.method == "getFileUrl") {
		const fileUrl = await db.collection("item").where({
			_id: data._id,
			user_id: data.key,
			password: data.password
		}).orderBy("time", "desc").field(
			"url,password_mode,password"
		).get({
			getOne: true
		});
		if (fileUrl.data) {
			if (fileUrl.data.password_mode == true) {
				if (fileUrl.data.password == data.password) {
					return {
						msg: "获取成功",
						code: 200,
						data: fileUrl.data.url
					}
				} else {
					return {
						msg: "密码错误",
						code: 400
					}
				}
			} else {
				return {
					msg: "获取成功",
					code: 200,
					data: fileUrl.data.url
				}
			}
		} else {
			return {
				msg: "文件不存在",
				code: 400
			}
		}
	} else {
		return {
			msg: "方法不存在",
			code: 400
		}
	}
};